<template>
    <div>
        <!-- 面包屑 导航区 -->
        <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 搜索框 -->
            <el-row :gutter="20">
                <el-col :span="10">
                    <el-input v-model="queryInfo.search" style="max-width: 600px" placeholder="请输入内容" clearable
                        @clear="getUserList">
                        <template #append>
                            <el-button>
                                <el-icon>
                                    <Search />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="addDialogVisible = true">
                        添加用户
                    </el-button>
                </el-col>
            </el-row>
            <!-- 用户列表信息区域 -->
            <el-table :data="userList" stripe border style="width: 100%">
                <el-table-column type="index" label="#" />
                <el-table-column prop="userName" label="用户名" />
                <el-table-column prop="userEmail" label="邮箱" />
                <el-table-column prop="userAge" label="年龄" />
                <el-table-column prop="userPhone" label="手机号" />
                <el-table-column prop="userDevicetoken" label="APNs Token" line />
                <el-table-column label="状态" v-slot="scope">
                    <el-switch v-model="scope.row.userRegistrationtime" active-value="1" inactive-value="0"
                        @change="userStateChange(scope.row)" />
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template v-slot="scope">
                        <el-button type="primary" circle @click="showEditDialog(scope.row.userId)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </el-button>
                        <el-button type="danger" circle @click="removeUserById(scope.row.userId)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                        <el-tooltip class="box-item" effect="dark" content="分配角色" placement="top">
                            <el-button type="warning" circle>
                                <el-icon>
                                    <Setting />
                                </el-icon>
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页内容 -->
            <div class="demo-pagination-block">
                <el-pagination current-page="queryInfo.page + 1" v-model:page-size="queryInfo.size"
                    :page-sizes="[1, 2, 5, 10, 20]" :size="size" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 添加用户对话框 -->
        <el-dialog v-model="addDialogVisible" title="添加用户" width="500" align-center @closed="resetAddDialogData">
            <!-- 内容区域 -->
            <el-form ref="addFormRef" style="max-width: 600px" :model="addForm" :rules="addFormRules" label-width="auto"
                status-icon>
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="addForm.userName" />
                </el-form-item>
                <el-form-item label="密码" prop="userPassword">
                    <el-input v-model="addForm.userPassword" type="password" show-password="false" />
                </el-form-item>
                <el-form-item label="邮箱" prop="userEmail">
                    <el-input v-model="addForm.userEmail" />
                </el-form-item>
                <el-form-item label="手机号" prop="userPhone">
                    <el-input v-model="addForm.userPhone" />
                </el-form-item>
                <el-form-item label="年龄" prop="userAge">
                    <el-input v-model="addForm.userAge" />
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addUser">
                        添加
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 修改用户对话框 -->
        <el-dialog v-model="editDialogVisible" title="修改用户信息" width="500" align-center @closed="resetEditDialogData">
            <!-- 内容区域 -->
            <el-form ref="editFormRef" style="max-width: 600px" :model="editForm" :rules="editFormRules"
                label-width="auto" status-icon>
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="editForm.userName" disabled />
                </el-form-item>
                <el-form-item label="邮箱" prop="userEmail">
                    <el-input v-model="editForm.userEmail" />
                </el-form-item>
                <el-form-item label="手机号" prop="userPhone">
                    <el-input v-model="editForm.userPhone" />
                </el-form-item>
                <el-form-item label="年龄" prop="userAge">
                    <el-input v-model="editForm.userAge" />
                </el-form-item>
                <el-form-item label="APNs" prop="userDevicetoken">
                    <el-input v-model="editForm.userDevicetoken" disabled />
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="editUserById()">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 获取用户列表参数兑现
            queryInfo: {
                // 当前页
                page: 0,
                // 每页显示多少条
                size: 2,
                // 搜索内容
                search: ''
            },
            userList: [],
            total: 0,
            // 添加用户对话框
            addDialogVisible: false,
            // 修改用户对话框
            editDialogVisible: false,
            // 添加用户表单数据
            addForm: {
                userName: '',
                userPassword: '',
                userEmail: '',
                userPhone: '',
                userAge: ''
            },
            // 查询到的用户信息数据
            editForm: {
            },
            // 添加用户表单验证规则
            addFormRules: {
                userName: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                userPassword: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ],
                userEmail: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
                ],
                userPhone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' }
                ],
                userAge: [
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                return callback(new Error('请输入年龄'))
                            }
                            const age = Number(value)
                            if (isNaN(age) || !Number.isInteger(age)) {
                                callback(new Error('请输入数字'))
                            } else {
                                if (value < 18) {
                                    callback(new Error('年龄必须大于18岁'))
                                } else {
                                    callback()
                                }
                            }
                        },
                        required: true,
                        trigger: 'blur'
                    }
                ]
            },
            // 修改用户表单验证规则
            editFormRules: {
                userName: [
                    { message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                userEmail: [
                    { message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
                ],
                userPhone: [
                    { message: '请输入手机号', trigger: 'blur' },
                    { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' }
                ],
                userAge: [
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                return callback(new Error('请输入年龄'))
                            }
                            const age = Number(value)
                            if (isNaN(age) || !Number.isInteger(age)) {
                                callback(new Error('请输入数字'))
                            } else {
                                if (value < 18) {
                                    callback(new Error('年龄必须大于18岁'))
                                } else {
                                    callback()
                                }
                            }
                        },
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    created() {
        this.getUserList()
    },
    methods: {
        getUserList() {
            this.$http.get('/api/carhome/user', { params: this.queryInfo }).then(res => {
                console.log(res)
                if (res.status === 200) {
                    this.userList = res.data.content
                    this.total = res.data.totalElements
                } else {
                    this.$message.error('获取用户列表失败')
                }
            }).catch(err => {
                console.log(err)
                this.$message.error('获取用户列表失败')
            })
        },
        // 监听 pagesize 改变事件
        handleSizeChange(val) {
            this.queryInfo.size = val
            this.getUserList()
        },
        // 监听 页码值 改变时间
        handleCurrentChange(val) {
            this.queryInfo.page = val - 1
            this.getUserList()
        },
        // 监听 switch 状态改变事件
        userStateChange(row) {
            console.log(row)
            this.$http.post('/api/carhome/user/updateUserInfo', { userID: row.userId, userRegistrationtime: row.userRegistrationtime }).then(res => {
                if (res.status === 200) {
                    this.$message.success('修改状态成功')
                    this.getUserList()
                } else {
                    this.$message.error('修改状态失败')
                }
            }).catch(err => {
                console.log(err)
                this.$message.error('修改状态失败')
            })
        },
        searchUserInfo() {
            this.getUserList()
        },
        // 监听 对话框关闭事件
        resetAddDialogData() {
            // 重置 对话框数据
            this.$refs.addFormRef.resetFields()
        },
        resetEditDialogData() {
            // 重置 对话框数据
            this.$refs.editFormRef.resetFields()
        },
        // 添加用户
        addUser() {
            this.$refs.addFormRef.validate(valid => {
                if (!valid) return
                this.$http.post('/api/carhome/user', this.addForm).then(res => {
                    console.log(res)
                    if (res.status === 200) {
                        // 隐藏添加用户对话框
                        this.addDialogVisible = false
                        this.$message.success('添加用户成功')
                        // 刷新用户列表
                        this.getUserList()
                    } else {
                        this.$message.error('添加用户失败')
                    }
                }).catch(err => {
                    this.$message.error('添加用户失败' + err)
                })
            })
        },
        // 删除用户
        removeUserById(id) {
            this.$confirm(
                '确认删除？此操作将永久删除该用户信息不可恢复',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(() => {
                this.$http.delete('/api/carhome/user?id=' + id).then(res => {
                    if (res.status === 200) {
                        this.$message.success({ type: '成功', message: '删除成功' })
                        this.getUserList()
                    } else {
                        this.$message.error('删除失败')
                    }
                }).catch(err => {
                    this.$message.error('删除失败' + err)
                })
            }).catch(() => {
                this.$message({
                    type: '信息',
                    message: '操作已取消'
                })
            })
        },
        // 展示编辑信息对话框
        showEditDialog(id) {
            console.log(id)
            this.editDialogVisible = true
            this.$http.get('/api/carhome/user/' + id).then(res => {
                console.log(res)
                if (res.status === 200) {
                    this.editForm = res.data
                } else {
                    this.$message.error('获取用户信息失败')
                }
            }).catch(err => {
                this.$message.error('获取用户信息失败' + err)
            })
        },
        editUserById() {
            this.$refs.editFormRef.validate(valid => {
                if (!valid) return
                // 发起网络请求修改用户信息
                this.updateUserInfo()
            })
        },
        // 发起网络请求修改用户信息
        updateUserInfo() {
            this.$http.post('/api/carhome/user/updateUserInfo', {
                userID: this.editForm.userId,
                userPhone: this.editForm.userPhone,
                userEmail: this.editForm.userEmail,
                userAge: this.editForm.userAge
            }).then(res => {
                if (res.status === 200) {
                    this.editDialogVisible = false
                    this.$message.success('修改用户信息成功')
                    this.getUserList()
                } else {
                    this.$message.error('修改用户信息失败')
                }
            }).catch(err => {
                this.$message.error('修改用户信息失败' + err)
            })
        }
    }
}
</script>

<style lang="less" scoped>
.el-table {
    margin-top: 20px;
    margin-bottom: 20px;
}
</style>
